$(function(){
	var _id = parseInt($_GET['id'] ? $_GET['id'] : 0);
	/**
	 * @desc 商品信息
	 */
	var global_pay = {
//			'page': $_GET['page'] ? $_GET['page'] : undefined,//页码
//			'pageSize' : $_GET['pageSize'] ? $_GET['pageSize'] : undefined, //页数
			'vendor': undefined,//往来单位
			'starTime': undefined,//开始时间
			'endTime' : undefined,//截至时间
			'name' : undefined,
	}
	var global_count = 1;
	var global_remove = [];
	var global_vendor = 0;
	var select_units;
	//时间
	dateSelFun($('#payment_date'));
	

	if(_id){
		$('#explode').show();
		initPayment();
		$("#bb").show();
	}
	/**
	 * @初始化页面
	 */
	function initPayment() {
		$('#confirm').show();
		$('#save').attr('data-id',parseInt(_id));
		$.get('get-vendor-payment-info', {'id' : _id}, function(data, status) {
			if(status =='success' && data.Ack =='Success'){
				var H = data.Body.head;
				if(H){
					$('#payment_no').val(H.vendor_payment_no);
					$('#payment_date').val(intToLocalDate(H.payment_date,1));
					$('#handle_man').val(H.handle_man);
					$('#vendor').val(H.vendor_id);
					$('#remark').val(H.remark);
					$('#account_name').val(H.account_name);
					$('#account_bank').val(H.account_bank);
					$('#account').val(H.account);
					$('#total_amount').val(H.total_amount);
					$('#create_man').val(H.username).attr('data-id', H.create_man);
					$('#remark').val(H.remark);
					$('#department').val(H.department);
					global_vendor = H.vendor_id;
					if(+H.confirm_flag){
						$('#save').attr('style','display:none');
						$('#confirm').removeClass().addClass('btn btn-warning btn-sm pull-right').attr('disabled','disabled');
					}
				}
				var D = data.Body.det;
				if(D){
					$('#stockList').find('tr').remove();
					var total_payamount = 0;
					for(var i in D){
						var tmp_units= '';
						var U = D[i].product_unit;
						tmp_units = '<select class="form-control units" disabled><option value="0" data-rate="0"> </option>';
						for(var j in U){
							tmp_units +='<option value="'+U[j].unit_id+'" data-rate="'+U[j].rate+'">'+U[j].unit_name+'</option>';
						}
						tmp_units +='</select>';
						
						$('<tr>'
							+'<td class="text-center" name="ids" data-id="'+D[i].vendor_payment_det_id+'" data-pid="'+D[i].purchase_id+'" data-did="'+D[i].purchase_det_id+'">'+global_count+'</td>'
							+'<td class="text-center" name="product"><a href="javascript:void(0)" class="stock-minus-tr" data-id="'+D[i].product_id+'"> <i class="fa fa-minus-circle" style="color:red;"></i>'
							+'</a></td>'
							+'<td class="text-center" name="name">'
							+'<input title="商品名称" type="text" value="'+D[i].product_name+'" data-id="'+D[i].product_id+'"'
							+'class="product stock-input50" readonly '
							+'style="height: 30px;width:80%"> <a class="search-btn search-product" title="搜索"'
							+'href="javascript:void(0)"><i class="fa fa-search"></i></a></td>'
							+'<td class="text-center" name="purchase_date"><input title="进货日期" type="text" value="'+intToLocalDate(D[i].purchase_time,1)+'" disabled></td>'
							+'<td class="text-center" name="quantity"><input title="数量" type="text" value="'+D[i].quantity+'" disabled></td>'
							+'<td class="text-center" name="unit" style="width:8%;" disabled data-unit ="'+D[i].quantity_unit+'">'+tmp_units+'</td>'
							+'<td class="text-center" name="price"><input title="单价" type="text"  value="'+D[i].price+'" disabled></td>'
							+'<td class="text-center" name="amount"><input title="金额" type="text" value="'+D[i].amount+'" class="amount" readonly></td>'
							+'<td class="text-center" name="remark"><input title="备注" type="text" value="'+D[i].remark+'"></td>'		
						   +'</tr>').appendTo('#stockList');
						$('#stockList').find('tr:last').find('[name="unit"] select').val(D[i].quantity_unit);
						global_count++;
						total_payamount += +D[i].amount;
					}
					$('#total_payamount').val(total_payamount);
				}
				
				//汇总
				var S = data.Body.sum;
				if(S){
					$('#summaryList').find('tr').remove();
					var total_payamount = 0;
					var _TIME = 0;
					for(var i in S){
						_TIME = S[i].summary_time;
						$('<tr>'
							+'<td class="text-center" name="ids" data-id="'+S[i].vendor_payment_det_id+'" data-pid="'+S[i].purchase_id+'" data-did="'+S[i].purchase_det_id+'">'+(+i+1)+'</td>'
							+'<td class="text-center" name="name">'
							+'<input title="商品名称" type="text" value="'+S[i].product_name+'" data-id="'+S[i].product_id+'"'
							+'class="product stock-input50" readonly '
							+'style="height: 30px;width:80%"></td>'
							+'<td class="text-center" name="purchase_date"><input title="进货日期" type="text" value="'+S[i].time+'" disabled></td>'
							+'<td class="text-center" name="quantity"><input title="数量" type="text" value="'+S[i].quantity+'" disabled></td>'
							+'<td class="text-center" name="unit" style="width:8%;" disabled data-unit ="'+S[i].quantity_unit+'">'+S[i].unit_name+'</td>'
							+'<td class="text-center" name="price"><input title="单价" type="text"  value="'+S[i].price+'" disabled></td>'
							+'<td class="text-center" name="amount"><input title="金额" type="text" value="'+S[i].amount+'" class="amount" readonly></td>'
							+'<td class="text-center" name="remark"><input title="备注" type="text" value="'+S[i].remark+'" readonly></td>'		
						   +'</tr>').appendTo('#summaryList');
						total_payamount += +S[i].amount;
					}
					
					$('#summary_amount').val(total_payamount);
					$('#save').attr('data-sum-time',_TIME);
				}
			}
		});
	};
	
	
	/**
	 * @desc 选择应付单
	 */
	$('#stockList').on('click','.search-product',function(){
		dateSelFun($('#starTime'));
		dateSelFun($('#endTime'));
		dateSelFun($('#payment_date'));
		$('#starTime').val('');
		$('#endTime').val('');
		$('#origin_id').val('');
		global_pay.starTime = undefined;
		global_pay.endTime = undefined;
		global_pay.name = undefined;
//		$('#checkAll').prop('checked',false);
//		global_pay.page = 1;
		$('#chooseOrigin').modal('show');
		$('#origin_header').empty();
//		getOriginMent();
		
	})
	
	//过滤
	$('#searchPay').on('click', function() {
		var _name = trim($('#origin_id').val());
		global_pay.name = _name;
		var starTime = $('#starTime').val();
		var endTime = $('#endTime').val();
		if(starTime.length ==0){
			alertTips('warning', '请输入开始查询时间');
			return false;
		}
			
		if(starTime > endTime){
			alertTips('warning','开始时间不能大于截至时间！');
			return false;
		}
		global_pay.starTime = starTime;
		global_pay.endTime = endTime;
		getOriginMent();
		return;
	})
	
	/**
	 * @desc 获取应付帐单
	 * @date 2017-03-03
	 */
	function getOriginMent(pageInfo)
	{
//		if(pageInfo !== undefined){
//			global_pay.page = pageInfo.page;
//			global_pay.pageSize = pageInfo.pageSize;
//		}
		global_pay.vendor = $('#vendor').val();
		if(global_pay.vendor == 0){
			alertTips('error','请先选择往来单位');
			return false;
		}
		$('#origin_header').find('tr').remove();
		var first_id = 0;
		var ii = layer.load();
		$.ajax({
            url: 'get-purchase-by-vendor',
            type: "GET",
            cache: true,
            data: global_pay,
            dataType: "json",
            jsonp: "callback",
            global:false,
            success: function(data){
           	 layer.close(ii);
           	 var P = data.Body.list;
					if(P && P.length){
						for(var i in P){
							var tmp_units = ''
								var U = P[i].product_unit;
								tmp_units = '<select class="form-control units" disabled><option value="0" data-rate="0"> </option>';
								for(var j in U){
									tmp_units +='<option value="'+U[j].unit_id+'" data-rate="'+U[j].rate+'">'+U[j].unit_name+'</option>';
								}
							$('<tr>'
							+'<td class="text-center"><input type="checkbox" class="ids" date-det-id="'+P[i].purchase_det_id+'" data-id="'+P[i].purchase_id+'" checked></td>'
							+'<td class="text-center">'+(+i+1)+'</td>'
							+'<td class="text-center date">'+intToLocalDate(P[i].purchase_date,1)+'</td>'
							+'<td class="text-center no" >'+P[i].purchase_no+'</td>'
							+'<td class="text-center product" data-id="'+P[i].goods_id+'">'+P[i].product_name+'</td>'
							+'<td class="text-center unit" data-id="'+P[i].quantity_unit+'">'+P[i].unit_name+'</td>'
							+'<td class="text-center quantity">'+P[i].quantity+'</td>'
							+'<td class="text-center price">'+P[i].price+'</td>'
							+'<td class="text-center amount">'+P[i].amount+'</td>'
							+'<td class="text-center remark" data-unit="'+encodeURI(tmp_units)+'">'+P[i].remark+'</td>'
							+'</tr>').appendTo('#origin');
						}
						first_id = P[0].procurement_id;//记录第一个id
//						var pageInfo = data.Body.page;
//			            if (typeof pageInfo !== 'undefined'){
//			              	refreshPaginationNavBar2($('.paginationNavBar'), pageInfo.page, pageInfo.pageSize, data.Body.count, getOriginMent);
//			            }
			            
					}else {
						$('<tr><td colspan="11" class="text-center">没有数据</td></tr>').appendTo('#origin_header');
//						refreshPaginationNavBar2($('.paginationNavBar'), 1, 10, 1, getOriginMent);
					}
//					$('#chooseOrigin').modal('show');//选择订单窗口
					
            }
		})
		
	}
	
	/**
	 * @desc 全选应付单
	 */
	$('#checkAll').on('click', function(){
		if($(this).prop('checked')){
			$('.ids').prop('checked', true);
		} else {
			$('.ids').prop('checked',false);
		}
	})
	
	$('#choosiePay').on('click',function(){
		$('#save').attr('data-sum-time',($('#starTime').val() + '*'+$('#endTime').val()));
		
		if(global_count == 1){
			$('#stockList').find('tr').remove();
		}
		var choose_flag = 0;
		var total_amount = 0 ;
		$('#origin_header').find('tr').each(function(index,element){
			var flag = $(element).find('.ids').prop('checked');
			if(flag){
				choose_flag = 1;
				var purchase_id = $(element).find('.ids').attr('data-id');
				var purchase_det_id = $(element).find('.ids').attr('date-det-id');
				var check_flag = 0;
				$('#stockList').find('[name="ids"]').each(function(ii,ele){
					if(purchase_id == $(ele).attr('data-pid') && purchase_det_id == $(ele).attr('data-did')){
						check_flag = 1;
					}
				})
				if(check_flag){
					return;
				}
				var no =  $(element).find('.no').text();
				var amount = +$(element).find('.amount').text();
				var remark = $(element).find('.remark').text();
				var product_id = $(element).find('.product').attr('data-id');
				var product_name = $(element).find('.product').text();
				var unit = $(element).find('.unit').attr('data-id');
				var price = $(element).find('.price').text();
				var quantity = $(element).find('.quantity').text();
				var purchase_date = $(element).find('.date').text();
				var tmp_units = decodeURI($(element).find('.remark').attr('data-unit'));
				
				
				
				total_amount += amount;
				
				$('<tr>'
				   +'<td class="text-center" name="ids" data-id="" data-pid="'+purchase_id+'" data-did="'+purchase_det_id+'">'+global_count+'</td>'
				   +'<td class="text-center" name="product"><a href="javascript:void(0)" class="stock-minus-tr"> <i class="fa fa-minus-circle" style="color:red;"></i>'
				   +'</a></td>'
				   +'<td class="text-center" name="name">'
				   +'<input title="商品名称" type="text" value="'+product_name+'" data-id="'+product_id+'"'
				   +'class="product stock-input50" readonly '
				   +'style="height: 30px;width:80%"> <a class="search-btn search-product" title="搜索"'
				   +'href="javascript:void(0)"><i class="fa fa-search"></i></a></td>'
				   +'<td class="text-center" name="purchase_date"><input title="进货日期" type="text" value="'+purchase_date+'" disabled></td>'
				   +'<td class="text-center" name="quantity"><input title="数量" type="text" value="'+quantity+'" disabled></td>'
				   +'<td class="text-center" name="unit" style="width:8%;">'+tmp_units+'</td>'
				   +'<td class="text-center" name="price"><input title="单价" type="text"  value="'+price+'" disabled></td>'
				   +'<td class="text-center" name="amount"><input title="金额" type="text" value="'+amount+'" class="amount" readonly></td>'
				   +'<td class="text-center" name="remark"><input title="备注" type="text" value="'+remark+'"></td>'
				   +'').appendTo('#stockList')
				   $('#stockList').find('tr:last').find('[name="unit"]').find('.units').val(unit);
				   global_count++;
			}
			
			
		})
		var current_amount = +$('#total_payamount').val();
			$('#total_payamount').val(current_amount + total_amount);
			$('#total_amount').val(current_amount + total_amount);
		if(!choose_flag){
			alertTips('warning','请勾选付款明细！');
			return false;
		}
	});
	
	//删除数据
	$('#stockList').on('click','.stock-minus-tr',function(){
		var tmp_id = $(this).closest('td').prev('td').attr('data-id');
		if ($.inArray(tmp_id, global_remove) >= 0) {
			return false;
		}
		if(tmp_id){
			global_remove.push({'vendor_payment_det_id':tmp_id});
		}
		
		
		if(global_count == 1){
			return false;
		} else if(global_count == 2){
			//添加一条数据要删除数据 后插入一条空数据
			$('#stockList').find('tr:first').remove();
			global_count--;
			insertOrginHtml();
			SumAmount();
			return false;
		} else {
			var self = $(this);
			//判断当前要删除的行,下面是否还有记录
            var nextTr = self.parent().parent().next('tr');
            if(nextTr.length){
            	//存在下一行，清空当前行数据
                self.closest('tr').remove();
                // 序号重新排列
                var td = $('#stockList').find('tr').find('td:first');
                $.each(td, function(index, item) {
                    var item = $(item);
                    item.text(index+1);
                })
                global_count--;
                SumAmount();
                return false;
            } else{
            	//删除的为最后一行
                self.closest('tr').remove();
                global_count--;
                SumAmount();
                return false;
            }
		}
		
	});
	
	/**
	 * @var 计算总金额
	 */
	var SumAmount = function(){
		var total_payamount = 0;
		$('#stockList tr').find('.amount').each(function(index,element){
			var _amount = $(element).val();
			if(_amount ==''){
				
			} else {
				total_payamount += +_amount;
			}
			
		})
		
		$('#total_payamount').val(total_payamount);
		$('#total_amount').val(total_payamount);
		
	};
	(function(){
		select_units = '<select title="单位" class="form-control unit">'
			+ '<option value="0">单位</option>'
			+ '<option value="6">个</option>'
			+ '<option value="5">支</option>'
			+ '<option value="4">包</option>'
			+ '<option value="2">斤</option>'
			+ '<option value="1">箱</option>' + '</select>';
	})();
	
	var insertOrginHtml = function(){
		$('<tr>'
				+'<td class="text-center" name="ids" data-id="" data-pid="" data-did="">'+global_count+'</td>'
				+'<td class="text-center"><a href="javascript:void(0)" class="stock-minus-tr"> <i class="fa fa-minus-circle" style="color:red;"></i>'
				+'</a></td>'
				+'<td class="text-center"  name="name">'
				+'<input title="商品名称" type="text" value="" data-id=" "'
				+'class="product stock-input50" readonly '
				+'style="height: 30px;width:80%"> <a class="search-btn search-product" title="搜索"'
				+'href="javascript:void(0)"><i class="fa fa-search"></i></a></td>'
				+'<td class="text-center" name="purchase_date"><input title="进货日期" type="text" value=""></td>'
				+'<td class="text-center" name="quantity"><input title="数量" type="text" value=""></td>'
				+'<td class="text-center" name="unit" style="width:8%;">'+select_units+'</td>'
				+'<td class="text-center" name="price"><input title="单价" type="text"  value=""></td>'
				+'<td class="text-center" name="amount"><input title="金额" type="text" value="" class="amount" readonly></td>'
				+'<td class="text-center" name="remark"><input title="备注" type="text" value=""></td>'
				+'</tr>').appendTo('#stockList');
	};
	(function(){
		$('#vendor').on('change',function(){
			var current_vendor = $(this).val();
			var tmp_flag = 0;
			if(global_count == 1){
				var pid = $('#stockList').find('.stock-minus-tr').data['id'];
				if(pid != undefined){
					tmp_flag = 1;
				} ;
			}else{
				tmp_flag =1;
			}
			if(tmp_flag){
				layer.confirm('更换供应商，明细将被清除，是否继续?', function(index) {
	                var td = $('#stockList').find('tr').find('td:first');
	                $.each(td, function(index, item) {
	    				var tmp_id = $(item).attr('data-id');
	    				if ($.inArray(tmp_id, global_remove) >= 0) {
	    					return false;
	    				}
	    				if(tmp_id){
	    					global_remove.push({'vendor_payment_det_id':tmp_id});
	    				}
	                })
					$('#stockList').find('tr').remove();
					global_count =1;
					insertOrginHtml();
					getBankAccount(current_vendor);

					global_vendor = current_vendor;
					layer.close(index);
				},function(index){
					$('#vendor').val(global_vendor);
					layer.close(index);
				});
			} else{
				getBankAccount(current_vendor);
				global_vendor = current_vendor;
			}
			
		})		
	})();
	
	//获取供应银行账户
	function getBankAccount(vendor)	{
		$.get('get-account-by-vendor', {'vid' : vendor}, function(data,status){
			if(status =='success') {
				if(data.Ack  =='Success') {
					var B = data.Body;
					$('#account_name').val(B.account_name);
					$('#account_bank').val(B.bank);
					$('#account').val(B.bank_account);
				}
			} else {
				alertTips('error','网络错误');
				return false;
			}
		})
	}
	
	$('#stockList').on('click','.product',function(){
		var name = $(this).val();
		if(name !=undefined){
			layer.tips(name, $(this), {
				  tips: [4, '#78BA32']
			});
		}
	});
	
	(function() {
		// 保存
		$('#save').on('click', function() {
			//单头
			var head = payment_header();
			if(!head){
				return false;
			}
			//明细
			var detail = payment_detail();
			if(!detail){
				return false;
			}
			var sumtime = $(this).attr('data-sum-time');
			var ii = layer.load();
			$.get('save-vendor-payment',{'head':head,'det':detail,'remove': global_remove,'id':_id,'sumtime': sumtime}, function(data,status){
				setTimeout(function(){
					  layer.close(ii);
				}, 1000);
				if(status =='success'){
					if(data.Ack =='Success'){
						alertTips('success','保存成功');
						setTimeout(function() {
 							window.location.reload();
						}, 1000);
					}
				} else {
					alertShows('error','网络错误');
				}
			})
		});

	})();	

	var payment_header = function() {
		var no = $('#payment_no').val();
		var payment_date = $('#payment_date').val();
		if (payment_date.length == 0) {
			alertTips('warning', '请输入申请时间');
			return false;
		}
		var department = $('#department').val();
		if(!+department){
			alertTips('warning','请选择部门！');
			return false;
		}
		var vendor = $('#vendor').val();
		if (!+vendor) {
			alertTips('warning', '请选择供应商');
			return false;
		}
		var handle_man = $('#handle_man').val();
		if (!+handle_man) {
			alertTips('warning', '请选择经手人员');
			return false;
		}
		
		var account_name = $('#account_name').val();
		if(account_name.length == 0){
			alertTips('warning','请选择账户名称！');
			return false;
		}
		var account_bank = $('#account_bank').val();
		if(account_bank.length ==0){
			alertTips('warning','请选择开户银行！');
			return false;
		}
		var account = $('#account').val();
		if(account.length ==0){
			alertTips('warning','请选择银行帐号！');
			return false;
		}
		
		var remark = $('#remark').val();
		var create_man = $('#create_man').attr('data-id');
		var payment_head = {
			'vendor_payment_no' : no,
			'payment_date' : payment_date,
			'vendor_id' : vendor,
			'handle_man' : handle_man,
			'department' : department,
			'create_man' : create_man,
			'account_name' : account_name,
			'account_bank' : account_bank,
			'account' : account,
			'total_amount':$('#total_amount').val(),
			'remark' : remark,
		};
		return payment_head;
	}
	
	//结算单明细
	var payment_detail = function(){
		var payment_det=[];
		var payment_info = [];
		var _tr = $('#stockList').find('tr');
		var flag = 1;
		if(_tr.length == 1){
			var pid = _tr.first('tr').find('td[name="ids"]').attr('data-pid');
			if(pid == ''){
				alertTips('warning','请选择付款明细');
				return false;
			}
		}
		_tr.each(function(index,element){
			var tr = $(this);
			var line_id = tr.find('[name="ids"]').attr('data-id');
			if(line_id == ''){
				line_id = 0;
			}
			var amount = tr.find('[name="amount"] input').val();
			var price = tr.find('[name="price"] input').val();
			
			payment_det = {
				'vendor_payment_det_id':line_id,
				'product_id' : tr.find('[name="name"] input').attr('data-id'),
				'purchase_time': tr.find('[name="purchase_date"] input').val(),
				'quantity' :tr.find('[name="quantity"] input').val(), 
				'quantity_unit' : tr.find('[name="unit"] select').val(),
				'price' : decimal(price,2),
				'amount' : decimal(amount,2),
				'remark' : tr.find('[name="remark"] input').val(),
				'purchase_id' : tr.find('[name="ids"]').attr('data-pid'),
				'purchase_det_id' : tr.find('[name="ids"]').attr('data-did'),
				
			};
			payment_info.push(payment_det);
			payment_det = [];
		});
		if(!flag){
			product_info = [];
			return false;
		}
		if(payment_info.length == 0){
			alertTips('warning','请选择产品！');
			return false;
		}
		return payment_info;
	}
	
	
	/**
	 * @desc 导出请款单
	 */
	$('#explode').on('click',function(){
		$.get('check-explode-vendor-payment',function(data,status){
			if(data.Error =='User authentication fails'){
				alertTips('error','你没有操作权限，如要操作，请向管理员申请');
				return;
			} else {
				$url ='explode-vendor-payment?id='+_id;
				window.location.href = $url;
			}
		})
	});
	
	
	//汇总导出
	
	$('#explodeSum').on('click',function(){
		$.get('check-explode-payment-summary',function(data,status){
			if(data.Error == 'User authentication fails'){
				alertTips('error','');
				return;
			} else {
				$url = 'explode-payment-summary?id='+_id;
				window.location.href = $url;
			}
		})
	})
})